﻿using OfficeOpenXml;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace TestFireBroadcastingHostPhone.ViewModel
{
    public class LogsQueryMV : ViewModelBase
    {
        /// <summary>
        /// 日志记录文件路径
        /// </summary>
        public const string logsdata = "C:\\盈帜软件配置\\RecordData\\Logs.txt";

        public static LogsQueryMV logsQueryMV { get;private set; }

        public LogsQueryMV()
        {
            logsQueryMV = this;
        }

        private ObservableCollection<DataItem> _logEntries;
        public ObservableCollection<DataItem> LogEntries
        {
            get => _logEntries;
            set
            {
                _logEntries = value;
                OnPropertyChanged(nameof(LogEntries));
            }
        }
        /// <summary>
        /// 绑定的日志表数据类
        /// </summary>
        public class DataItem
        {
            /// <summary>
            /// 测试产品型号
            /// </summary>
            public string? TestProduct { get; set; }
            /// <summary>
            /// 测试产品结果
            /// </summary>
            public string? TestResult { get; set; }
            /// <summary>
            /// 测试产品数量
            /// </summary>
            public string? TestNumber { get; set; }
            /// <summary>
            /// 测试产品人员
            /// </summary>
            public string? TestPerson { get; set; }
            /// <summary>
            /// 测试日期
            /// </summary>
            public string? TestTime { get; set; }
        }

        private ObservableCollection<QureyProduct> _productInfo;

        public ObservableCollection<QureyProduct> ProductTypeInfo
        {
            get => _productInfo;
            set
            {
                _productInfo = value;
                OnPropertyChanged(nameof(ProductTypeInfo));
            }
        }
        /// <summary>
        /// 绑定的产品型号数据类
        /// </summary>
        public class QureyProduct
        {
            /// <summary>
            /// 序号
            /// </summary>
            public string? ProductNumber { set; get; }
            /// <summary>
            /// 品号
            /// </summary>
            public string? ProductID { set; get; }
            /// <summary>
            /// 型号
            /// </summary>
            public string? ProductType { set; get; }
        }

        /// <summary>
        /// 日志表插入一行数据
        /// </summary>
        /// <param name="product">产品型号</param>
        /// <param name="result">测试结果</param>
        /// <param name="number">测试数量</param>
        /// <param name="person">测试人员</param>
        /// <param name="time">测试日期</param>
        public void DataGrid_Process_Add_Fun(string product, string result, string number, string person, string time, out string err_info)
        {
            err_info = string.Empty;
            // 初始化LogEntries集合，如果它还没有被初始化的话
            if (LogEntries == null)
            {
                LogEntries = new ObservableCollection<DataItem>();
            }
            var newItem = new DataItem
            {
                TestProduct = product,
                TestResult = result,
                TestNumber = number,
                TestPerson = person,
                TestTime = time
            };
            // 如果有错误处理逻辑，例如验证输入数据，则在此处添加
            if (string.IsNullOrEmpty(product))
            {
                err_info = "产品型号不能为空";
            }
            else if (string.IsNullOrEmpty(result))
            {
                err_info = "测试结果不能为空";
            }
            else if (string.IsNullOrEmpty(number))
            {
                err_info = "测试数量不能为空";
            }
            else if (string.IsNullOrEmpty(person))
            {
                err_info = "测试人员不能为空";
            }
            else if (string.IsNullOrEmpty(time))
            {
                err_info = "测试时间不能为空";
            }
            if (string.IsNullOrEmpty(err_info))
            {
                LogEntries.Add(newItem);
            }
        }

        
        /// <summary>
        /// 读取Txt文本内容到DataGrid控件中
        /// </summary>
        /// <param name="dataGrid">DataGrid控件</param>
        /// <param name="filePath">txt文本</param>
        public void ImportTxtToDataGrid(string filePath)
        {
            var lines = File.ReadAllLines(filePath);
            if (LogEntries == null)
            {
                LogEntries = new ObservableCollection<DataItem>();
            }
            foreach (var line in lines.Skip(1)) // 跳过表头
            {
                var values = line.Split('\t');
                if (values.Length >= 5)
                {
                    LogEntries.Add(new DataItem
                    {
                        TestProduct = values[0],
                        TestResult = values[1],
                        TestNumber = values[2],
                        TestPerson = values[3],
                        TestTime = values[4]
                    });
                }
            }
        }
        /// <summary>
        /// 读取Excel表格到DataGrid控件中
        /// </summary>
        /// <param name="filePath">表格路径</param>
        public void ImportExcelToDataGrid(string filePath)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            using (var package = new ExcelPackage(new FileInfo(filePath)))
            {
                var worksheet = package.Workbook.Worksheets[0]; // 假设数据在第一个工作表中
                var startRow = 2; // 假设第一行为表头
                if (_productInfo == null)
                {
                    _productInfo = new ObservableCollection<QureyProduct>();
                }
                else
                {
                    _productInfo.Clear(); // 清除旧数据
                }
                for (int row = startRow; row <= worksheet.Dimension.End.Row; row++)
                {
                    _productInfo.Add(new QureyProduct
                    {
                        ProductNumber = worksheet.Cells[row, 1].Text,
                        ProductID = worksheet.Cells[row, 2].Text,
                        ProductType = worksheet.Cells[row, 3].Text
                    });
                }
                OnPropertyChanged(nameof(ProductTypeInfo)); // 通知属性更改
            }
        }

        /// <summary>
        /// 绑定清空日志表格事件
        /// </summary>
        public ICommand Btn_CleanDataGridLogsQurey_Command => new RelayCommand(OnBtn_CleanDataGridLogsQurey);
        /// <summary>
        /// 清空日志表格
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_CleanDataGridLogsQurey(object obj)
        {
            string err_info = string.Empty;
            LogEntries.Clear();
            // 读取文件的所有行
            List<string> lines = new List<string>(File.ReadAllLines(logsdata));
            // 检查文件是否大于1行
            if (lines.Count > 1)
            {
                // 移除从第二行开始的所有行
                lines.RemoveRange(1, lines.Count - 1);
                File.WriteAllLines(logsdata, lines);
                MessageBox.Show("清除成功");
            }
            else
            {
                MessageBox.Show("清除失败");
            }
        }
    }
}
